<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
    <title>刮刮乐</title>

    <style>
        .wrapper {
            position: relative;
            width: 300px;
            height: 250px;
            background-color: #fcc;
        }

        .ticket {
            display: flex;
            position: absolute;
            inset: 0;
        }

        .label {
            margin: auto;
            color: #fff;
            font-size: 66px;
            user-select: none;
        }

        canvas {
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="ticket">
            <span class="label">一等奖</span>
        </div>
    </div>

    <script type="text/javascript">
        init()


        function init() {
            const wrapper = document.querySelector('.wrapper')
            const cvs = createScratchTicket(wrapper)
            const ctx = cvs.getContext('2d')
            wrapper.appendChild(cvs)

            setStyle(ctx)
            bindEvent(cvs, ctx)
        }


        function bindEvent(el, ctx) {
            el.onmousedown = function ({ clientX, clientY }) {
                ctx.moveTo(clientX, clientY)

                el.onmousemove = function ({ clientX, clientY }) {
                    ctx.lineTo(clientX, clientY)
                    ctx.stroke()
                }

                // 移出浏览器或元素时也会解绑
                // el.onmouseup = el.onmouseout = function () {
                el.onmouseup = function () {
                    el.onmousemove = null
                    el.onmouseup = null
                }
            }
        }

        function createScratchTicket(wrapper) {
            const cvs = document.createElement('canvas')
            const ctx = cvs.getContext('2d')
            cvs.width = wrapper.clientWidth
            cvs.height = wrapper.clientHeight

            // 绘制刮奖区域
            ctx.fillStyle = '#999'
            ctx.fillRect(0, 0, cvs.width, cvs.height)

            return cvs
        }

        function setStyle(ctx) {
            // 什么颜色都行
            ctx.fillStyle = 'transparent'
            ctx.lineWidth = 15
            ctx.lineCap = 'round'
            ctx.lineJoin = 'round'
        
            ctx.globalCompositeOperation = 'destination-out'
        }
    </script>
</body>

</html>